package com.chexiehui.jc.ui.fragment;

import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.aries.ui.view.radius.RadiusRelativeLayout;
import com.aries.ui.view.title.TitleBarView;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chexiehui.jc.AppApplication;
import com.chexiehui.jc.R;
import com.chexiehui.jc.adapter.FragmentViewPagerAdapter;
import com.chexiehui.jc.base.BaseModel;
import com.chexiehui.jc.base.BaseMvpFragment;
import com.chexiehui.jc.entity.BaiDuLocationInfo;
import com.chexiehui.jc.entity.HomeMenuInfo;
import com.chexiehui.jc.entity.HomeMenuResultInfo;
import com.chexiehui.jc.listener.IHomeRefreshFragment;
import com.chexiehui.jc.mvp.home.HomePageCovenant;
import com.chexiehui.jc.mvp.home.HomePagePresenter;
import com.chexiehui.jc.ui.activity.BrowseHistoryActivity;
import com.chexiehui.jc.ui.activity.BuyCarCalculateActivity;
import com.chexiehui.jc.ui.activity.CarGarageAssistantActivity;
import com.chexiehui.jc.ui.activity.ConditionalCarSelectionActivity;
import com.chexiehui.jc.ui.activity.ForumDynamicPostActivity;
import com.chexiehui.jc.ui.activity.LoanQuotaCalculateActivity;
import com.chexiehui.jc.ui.activity.LoanServicesListActivity;
import com.chexiehui.jc.ui.activity.MyFollowActivity;
import com.chexiehui.jc.ui.activity.NewCarListActivity;
import com.chexiehui.jc.ui.activity.SalesRankingListActivity;
import com.chexiehui.jc.ui.activity.SearchActivity;
import com.chexiehui.jc.ui.activity.Shop4sConsultActivity;
import com.chexiehui.jc.ui.activity.StagesBuyCarListActivity;
import com.chexiehui.jc.utils.BundleBuilder;
import com.chexiehui.jc.utils.GlideUtil;
import com.chexiehui.jc.utils.NoDoubleClickListener;
import com.chexiehui.jc.utils.NoDoubleClickUtils;
import com.chexiehui.jc.widget.NonSlidingGridView;
import com.flyco.tablayout.SlidingTabLayout;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class HomeFragment extends BaseMvpFragment<HomePagePresenter> implements HomePageCovenant.View {

    @BindView(R.id.titleBar)
    TitleBarView titleBar;
    @BindView(R.id.iv_item_search_icon)
    ImageView ivItemSearchIcon;
    @BindView(R.id.rrl_search_panel)
    RadiusRelativeLayout rrlSearchPanel;
    @BindView(R.id.stl_slide_table)
    SlidingTabLayout stlSlideTable;
    @BindView(R.id.vp_content_page)
    ViewPager vpContentPage;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.nsgv_menu_grid_first)
    NonSlidingGridView nsgvMenuGridFirst;
    @BindView(R.id.hsv_scroll_menu_first)
    HorizontalScrollView hsvScrollMenuFirst;
    @BindView(R.id.ll_first_menu_panel)
    LinearLayout llFirstMenuPanel;
    @BindView(R.id.nsgv_menu_grid_second)
    NonSlidingGridView nsgvMenuGridSecond;
    @BindView(R.id.hsv_scroll_menu_second)
    HorizontalScrollView hsvScrollMenuSecond;
    @BindView(R.id.ll_second_menu_panel)
    LinearLayout llSecondMenuPanel;
    @BindView(R.id.ctl_container)
    CollapsingToolbarLayout ctlContainer;
    @BindView(R.id.abl_bar)
    AppBarLayout ablBar;
    private BaiDuLocationInfo baiDuLocationInfo;

    private HomeMenuResultInfo menuResultInfo;

    public static HomeFragment getInstance() {
        HomeFragment fragment = new HomeFragment();
        return fragment;
    }

    private List<HomeMenuInfo> firstMenuData;
    private CommonAdapter<HomeMenuInfo> firstMenuAdapter;
    private List<HomeMenuInfo> secondMenuData;
    private CommonAdapter<HomeMenuInfo> secondMenuAdapter;
    private String[] titles;
    private ArrayList<Fragment> slideFragmentList = new ArrayList<>();
    private FragmentViewPagerAdapter pagerAdapter;
    private HomeSlideRecommendFragment homeSlideRecommendFragment;
    private HomeSlideFollowFragment homeSlideFollowFragment;
//    private HomeSlideNewCarFragment homeSlideNewCarFragment;
    private HomeSlide4sShopFragment homeSlide4sShopFragment;

    @Override
    protected void initTitleView(Bundle savedInstanceState) {
        titleBar.setTitleMainText(getStringSource(R.string.app_name))
                .setLeftTextDrawable(0)
                .setTitleMainTextFakeBold(true)
                .setRightTextDrawable(R.mipmap.ic_home_add)
                .setOnRightTextClickListener(new NoDoubleClickListener() {
                    @Override
                    public void onNoDoubleClick(View view) {
                        startActivity(ForumDynamicPostActivity.class);
                    }
                });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        baiDuLocationInfo = new BaiDuLocationInfo();
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mvpPresenter.getMenuData();
                refreshTabPage();
            }
        });
//        ablBar.setExpanded(true);
//        ablBar.setLiftable(false);
//        ablBar.setLiftOnScroll(false);
//        ablBar.setLifted(false);
        initFirstMenu();
        initSecondMenu();
        initContentPage();
        mvpPresenter.getMenuData();
        AppApplication.getInstances().getLocationService().registerListener(mListener);
    }

    private void refreshTabPage() {
        ((IHomeRefreshFragment) slideFragmentList.get(stlSlideTable.getCurrentTab())).onCallRefresh();

    }

    @Override
    public void onDestroy() {
        AppApplication.getInstances().getLocationService().unregisterListener(mListener); //注销掉监听
        super.onDestroy();
    }

    private void initFirstMenu() {
        firstMenuData = new ArrayList<>();
//        quickList.add(new HomeQuickInfo("4s店咨询", "官网合作", 0, Color.parseColor("#35B6FF"), Color.parseColor("#6C7BFF"), Shop4sConsultActivity.class));
//        quickList.add(new HomeQuickInfo("0息购车", "诚信交易", 0, Color.parseColor("#45E2BF"), Color.parseColor("#12B8B2"), LoanQuotaCalculateActivity.class));
//        quickList.add(new HomeQuickInfo("低息借款", "诚信交易", 0, Color.parseColor("#FF9D39"), Color.parseColor("#FF7167"), LoanServicesListActivity.class));
//        quickList.add(new HomeQuickInfo("分期购车", "信用生活", 0, Color.parseColor("#FF383F"), Color.parseColor("#FF67BE"), StagesBuyCarListActivity.class));
        firstMenuAdapter = new CommonAdapter<HomeMenuInfo>(mActivity, R.layout.item_home_quick, firstMenuData) {
            @Override
            protected void convert(ViewHolder holder, HomeMenuInfo item, int position) {
                holder.setText(R.id.tv_item_title, item.getTitle());
                holder.setText(R.id.tv_item_subtitle, item.getSubTitle());
                GlideUtil.loadImageViewCrop(mContext, item.getIcon(), holder.getView(R.id.iv_item_icon),
                        R.color.colorTransparent, R.color.colorTransparent);
                GradientDrawable aDrawable = new GradientDrawable(GradientDrawable.Orientation.TL_BR,
                        new int[]{Color.parseColor(StringUtils.isTrimEmpty(item.getGradient1()) ? "#35B6FF" : item.getGradient1()),
                                Color.parseColor(StringUtils.isTrimEmpty(item.getGradient2()) ? "#6C7BFF" : item.getGradient2())});
                aDrawable.setCornerRadius(SizeUtils.dp2px(5));
                holder.getConvertView().setBackground(aDrawable);
            }
        };
        nsgvMenuGridFirst.setOnItemClickListener((parent, view, position, id) -> {
            if (NoDoubleClickUtils.isDoubleClick()) return;
            startActivityByFlag(firstMenuData.get(position).getType());
        });
        nsgvMenuGridFirst.setAdapter(firstMenuAdapter);
    }

    private void startActivityByFlag(int flag){
        switch (flag){
            //4s店咨询
            case 10:
                startActivity(Shop4sConsultActivity.class, new BundleBuilder().
                        putSerializable("location", baiDuLocationInfo).create());
                break;
            case 11:
                //贷款额度测算
                startActivity(LoanQuotaCalculateActivity.class);
                break;
            case 12:
                //借款服务
                startActivity(LoanServicesListActivity.class);
                break;
            case 13:
                //分期购车列表
                startActivity(StagesBuyCarListActivity.class, new BundleBuilder().
                        putSerializable("location", baiDuLocationInfo).create());
                break;
            case 14:
                //二手车
                startActivity(CarGarageAssistantActivity.class, new BundleBuilder().
                        putSerializable("location", baiDuLocationInfo).create());
                break;
            case 15:
                //我的关注
                startActivity(MyFollowActivity.class);
                break;
            case 16:
                //浏览历史
                startActivity(BrowseHistoryActivity.class);
                break;
            case 20:
                //购车计算
                startActivity(BuyCarCalculateActivity.class);
                break;
            case 21:
                //条件选车
                startActivity(ConditionalCarSelectionActivity.class);
                break;
            case 22:
                //销量排行列表
                startActivity(SalesRankingListActivity.class);
                break;
            case 23:
                //新车发布列表
                startActivity(NewCarListActivity.class);
                break;
            default:
                showToast("开发中");
                break;
        }
    }

    private void initSecondMenu() {
        secondMenuData = new ArrayList<>();
//        actionList.add(new HomeActionInfo("购车计算", R.mipmap.ic_home_gcjs));
//        actionList.add(new HomeActionInfo("条件选车", R.mipmap.ic_home_tjsx));
//        actionList.add(new HomeActionInfo("销量排行", R.mipmap.ic_home_xlph));
//        actionList.add(new HomeActionInfo("新车发布", R.mipmap.ic_home_xcfb));
        secondMenuAdapter = new CommonAdapter<HomeMenuInfo>(mActivity, R.layout.item_home_action, secondMenuData) {
            @Override
            protected void convert(ViewHolder holder, HomeMenuInfo item, int position) {
                holder.setText(R.id.tv_item_label, item.getTitle());
                if(StringUtils.isTrimEmpty(item.getIcon())){
                    holder.setImageResource(R.id.iv_item_icon,
                            item.getTitle().equals("购车计算") ? R.mipmap.ic_home_gcjs :
                                    item.getTitle().equals("条件选车") ? R.mipmap.ic_home_tjsx :
                                            item.getTitle().equals("销量排行") ? R.mipmap.ic_home_xlph :
                                                    item.getTitle().equals("新车发布") ? R.mipmap.ic_home_xcfb : R.drawable.shape_circle
                    );
                }else{
                    GlideUtil.loadImageViewCrop(mContext, item.getIcon(), holder.getView(R.id.iv_item_icon),
                            R.drawable.shape_circle, R.drawable.shape_circle);
                }
            }
        };
        nsgvMenuGridSecond.setOnItemClickListener((parent, view, position, id) -> {
            if (NoDoubleClickUtils.isDoubleClick()) return;
            startActivityByFlag(secondMenuData.get(position).getType());

        });
        nsgvMenuGridSecond.setAdapter(secondMenuAdapter);
    }

    private void initContentPage() {
        titles = new String[]{"推荐", "关注"};
        homeSlideRecommendFragment = HomeSlideRecommendFragment.getInstance(0);
        homeSlideFollowFragment = HomeSlideFollowFragment.getInstance(1);
        //homeSlideNewCarFragment = HomeSlideNewCarFragment.getInstance(2);
        homeSlide4sShopFragment = HomeSlide4sShopFragment.getInstance(2);
        slideFragmentList.add(homeSlideRecommendFragment);
        slideFragmentList.add(homeSlideFollowFragment);
//        slideFragmentList.add(homeSlideNewCarFragment);
        //slideFragmentList.add(homeSlide4sShopFragment);
        stlSlideTable.setSnapOnTabClick(true);
        pagerAdapter = new FragmentViewPagerAdapter(getChildFragmentManager(), slideFragmentList, titles);
        vpContentPage.setAdapter(pagerAdapter);
        stlSlideTable.setViewPager(vpContentPage);
        vpContentPage.setOffscreenPageLimit(titles.length);
    }

    @OnClick({R.id.rrl_search_panel})
    public void onViewClicked(View view){
        switch (view.getId()){
            case R.id.rrl_search_panel:
                startActivity(SearchActivity.class);
                break;
        }
    }

    private void changeContentPage(String city, double lat, double lng) {
        /*if (titles.length == 2) {
            titles = new String[]{"推荐", "关注", city};
            if(slideFragmentList.size() == 2){
                slideFragmentList.add(homeSlide4sShopFragment);
                stlSlideTable.addNewTab(city);
            }
            homeSlide4sShopFragment.setAddressInfo(city, lat, lng);
            pagerAdapter.setTitles(titles);
//            pagerAdapter.notifyDataSetChanged();
        } else if (!titles[2].equals(city)) {
            titles[2] = city;
            homeSlide4sShopFragment.setAddressInfo(city, lat, lng);
            pagerAdapter.setTitles(titles);
            stlSlideTable.notifyDataSetChanged();
//            pagerAdapter.notifyDataSetChanged();
        }*/
        if (titles.length == 2 || !titles[titles.length-1].equals(city)) {
            AppApplication.getInstances().setPubCity(city);
            titles = new String[]{"推荐", "关注", city};
            slideFragmentList.clear();
            slideFragmentList = null;
            slideFragmentList = new ArrayList<>();
            pagerAdapter = null;
            homeSlideRecommendFragment.setHasLoadedOnce(false);
            slideFragmentList.add(homeSlideRecommendFragment);
            homeSlideFollowFragment.setHasLoadedOnce(false);
            slideFragmentList.add(homeSlideFollowFragment);
            homeSlide4sShopFragment.setHasLoadedOnce(false);
            slideFragmentList.add(homeSlide4sShopFragment);
            homeSlide4sShopFragment.setAddressInfo(city, lat, lng);
            stlSlideTable.setSnapOnTabClick(true);
            pagerAdapter = new FragmentViewPagerAdapter(getChildFragmentManager(), slideFragmentList, titles);
            vpContentPage.setAdapter(pagerAdapter);
            stlSlideTable.setViewPager(vpContentPage);
            vpContentPage.setOffscreenPageLimit(titles.length);
        }else{
            homeSlide4sShopFragment.setAddressInfo(city, lat, lng);
        }
    }

    private void changeFirstMenu() {
        if (menuResultInfo == null || menuResultInfo.getMenuList1().size() <= 0) {
            llFirstMenuPanel.setVisibility(View.GONE);
        } else {
            llFirstMenuPanel.setVisibility(View.VISIBLE);
            firstMenuData.clear();
            firstMenuData.addAll(menuResultInfo.getMenuList1());
            nsgvMenuGridFirst.setNumColumns(firstMenuData.size());
            BigDecimal columnWidth = BigDecimal.valueOf(ScreenUtils.getScreenWidth() - SizeUtils.dp2px(50)).divide(BigDecimal.valueOf(4),2, BigDecimal.ROUND_HALF_UP);
            nsgvMenuGridFirst.setColumnWidth(columnWidth.intValue());
            firstMenuAdapter.notifyDataSetChanged();
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) nsgvMenuGridFirst.getLayoutParams();
            //lp.width = SizeUtils.dp2px(80) * firstMenuData.size() + SizeUtils.dp2px(10) * (firstMenuData.size() - 1);
            lp.width = columnWidth.multiply(BigDecimal.valueOf(firstMenuData.size()))
                    .add(BigDecimal.valueOf(SizeUtils.dp2px(10)).multiply(BigDecimal.valueOf(firstMenuData.size() - 1))).intValue();
            nsgvMenuGridFirst.setLayoutParams(lp);
        }
    }

    private void changeSecondMenu() {
        if (menuResultInfo == null || menuResultInfo.getMenuList1().size() <= 0) {
            llSecondMenuPanel.setVisibility(View.GONE);
        } else {
            llSecondMenuPanel.setVisibility(View.VISIBLE);
            secondMenuData.clear();
            secondMenuData.addAll(menuResultInfo.getMenuList2());
            nsgvMenuGridSecond.setNumColumns(secondMenuData.size());
            if(secondMenuData.size() < 5){
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) nsgvMenuGridSecond.getLayoutParams();
                lp.width = ScreenUtils.getScreenWidth() - SizeUtils.dp2px(20);
                nsgvMenuGridSecond.setColumnWidth(lp.width/secondMenuData.size());
                nsgvMenuGridSecond.setLayoutParams(lp);
            }else{
                BigDecimal columnWidth = BigDecimal.valueOf(ScreenUtils.getScreenWidth() - SizeUtils.dp2px(50)).divide(BigDecimal.valueOf(4),2, BigDecimal.ROUND_HALF_UP);
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) nsgvMenuGridSecond.getLayoutParams();
                //lp.width = SizeUtils.dp2px(80) * secondMenuData.size() + SizeUtils.dp2px(10) * (secondMenuData.size() - 1);
                // nsgvMenuGridSecond.setColumnWidth(SizeUtils.dp2px(80));
                lp.width = columnWidth.multiply(BigDecimal.valueOf(secondMenuData.size()))
                        .add(BigDecimal.valueOf(SizeUtils.dp2px(10)).multiply(BigDecimal.valueOf(secondMenuData.size() - 1))).intValue();
                nsgvMenuGridSecond.setColumnWidth(columnWidth.intValue());
                nsgvMenuGridSecond.setLayoutParams(lp);
            }
            secondMenuAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected HomePagePresenter createPresenter() {
        return new HomePagePresenter(this);
    }

    @Override
    public void onGeMenuDataSuccess(BaseModel<HomeMenuResultInfo> successResult) {
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh(true);
        }
        menuResultInfo = successResult.getData();
        changeFirstMenu();
        changeSecondMenu();
    }

    @Override
    public void onGetMenuDataFailure(BaseModel<Object> failureResult) {
        if (refreshLayout.getState() == RefreshState.Refreshing) {
            refreshLayout.finishRefresh(false);
        }
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 0){
                BDLocation location = (BDLocation) msg.obj;
                baiDuLocationInfo.setCity(location.getCity());
                baiDuLocationInfo.setLat(location.getLatitude());
                baiDuLocationInfo.setLng(location.getLongitude());
                changeContentPage(location.getCity(), location.getLatitude(), location.getLongitude());
            }
        }
    };

    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                if(StringUtils.isTrimEmpty(location.getCity())){
                    return;
                }
                Message msg = new Message();
                msg.obj = location;
                msg.what = 0;
                handler.sendMessage(msg);

            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {
            super.onConnectHotSpotMessage(s, i);
        }

        @Override
        public void onLocDiagnosticMessage(int locType, int diagnosticType, String diagnosticMessage) {
            super.onLocDiagnosticMessage(locType, diagnosticType, diagnosticMessage);
        }
    };

}
